package com.xuecheng.search.config;

import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchConfig {

    /**
     * 读取配置文件
     */
    private final ElasticsearchProperties elasticsearchProperties;

    /**
     * 读取配置文件，创建RestHighLevelClient客户端
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 1. 解析hostList配置信息
        String[] split = elasticsearchProperties.getHostList().split(",");
        // 2. 创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String[] address = split[i].split(":");
            httpHostArray[i] = new HttpHost(address[0], Integer.parseInt(address[1]));
        }
        // 3. 创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }
}